import { Md5_16 } from '@/utils';
import notify from 'devextreme/ui/notify';
import { useEffect, useRef, useState } from 'react';
import { history, useModel } from 'umi';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import PageLoading from '../components/PageLoading';
import CommonCpasTable from './components';
import './index.less';
import { buildTbtable, getjudgmentInit, templateInitApi } from './service';

const ApprovedFinance = (props: any) => {
  const { initialState } = useModel('@@initialState');
  const { dbname, zcbfid, bsdw, sjnd } = initialState?.curPart;
  const [valIndex, setValIndex] = useState<string>('1');
  const { pathname, query }: any = history.location || {};
  const isAudit = useRef<any>(pathname.includes('unaudit/trend') ? '未审' : '审定');
  const basePath = '\\Tools';
  const currentTableName = useRef<any>(
    pathname.includes('unaudit/trend') ? '试算分析-资产负债表_未审' : '试算分析-资产负债表_审定',
  );

  const [spinLoad, setSpinLoad] = useState<boolean>(false);
  const [spinAntTabs, setSpinAntTabs] = useState<boolean>(true);

  const [excelParams, setExcelParams] = useState<any>([
    {
      cpastableParam: {
        tname: `试算分析-资产负债表_${isAudit.current}`,
        data_id: '',
        type: 'fs',
      },
      // tableTitle: "资产负债表",
      tableDate: ' ',
      isExportTableTitle: true,
      exportType: 'primary',
      isBatchExport: true,
    },
    {
      cpastableParam: {
        tname: `试算分析-利润表_${isAudit.current}`,
        data_id: '',
        type: 'fs',
      },
      // // tableTitle: "资产负债表（续）",
      tableDate: ' ',
      isExportTableTitle: true,
      exportType: 'primary',
      isBatchExport: true,
    },
  ]);

  const [antTabsData, setAntTabsData] = useState<any[]>([
    {
      tabName: '资产负债表',
      tabKey: '1',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: `试算分析-资产负债表_${isAudit.current}`,
        titleName: `资产负债表趋势分析`,
        WscwbbType: '资产类',
        origin: `${isAudit.current}财务`,
        tabsIndex: 1,
        CPASTableType: 'fs',
      },
    },
    {
      tabName: `利润表`,
      tabKey: '2',
      isVerify: false,
      closable: false,
      propsData: {
        tableName: `试算分析-利润表_${isAudit.current}`,
        titleName: `利润表表趋势分析`,
        WscwbbType: '负债类',
        origin: `${isAudit.current}财务`,
        tabsIndex: 2,
        CPASTableType: 'fs',
      },
    },
  ]);
  const refsCommonCpasTable = useRef<any>(null);

  const changeTabsKey = async (val: string) => {
    // setIsInitBtn(false);
    setValIndex(val);
    if (val === '2') {
      currentTableName.current = `试算分析-利润表_${isAudit.current}`;
    } else {
      currentTableName.current = `试算分析-资产负债表_${isAudit.current}`;
    }
    const res = await builtableStrute(val);
    await refsCommonCpasTable.current.CPASInit2(currentTableName.current, res);
  };

  /**
   * 生成表
   */
  const builtableStrute = async (valIndexT?: any) => {
    let valIndexTemp = valIndexT ? valIndexT : valIndex;

    // 当前是已审或者未审，eff 函数知道，存全局变量
    let AuditedTypeNames = ['审定财务-资产表'];
    let AuditedTypeNamesLi = ['审定财务-负债表'];
    let tb_names = [`${sjnd}_试算平衡-资产表_期末`, `${sjnd}_试算平衡-资产表_期初`];
    let ItemName_total = '资产总计';
    let now_year_cmap = 'SDS';
    if (isAudit.current === '未审') {
      if (valIndexTemp === '2') {
        AuditedTypeNames = ['未审财务报表-利润表'];
        // 利润本期  WSLJFSEWSLJFSE   SDLJFSE 审定
        now_year_cmap = 'WSLJFSE';
      } else {
        now_year_cmap = 'WSS';
        AuditedTypeNames = ['未审财务报表-资产表'];
        AuditedTypeNamesLi = ['未审财务报表-负债表'];
      }
    } else {
      if (valIndexTemp === '2') {
        AuditedTypeNames = ['审定财务-利润表'];
        now_year_cmap = 'SDLJFSE';
        // tb_analyisis_name = `试算分析-利润表_${isAudit.current}`
      }
    }
    if (valIndexTemp === '1') {
      const res = await buildTbtable({
        dbname: dbname,
        now_year_cmap: now_year_cmap,
        tb_analyisis_name: `试算分析-负债表_${isAudit.current}`,
        AuditedTypeNames: AuditedTypeNamesLi,
        tb_names: [`${sjnd}_试算平衡-负债表_期末`, `${sjnd}_试算平衡-负债表_期初`],
        tb_names_asset: [`${sjnd}_试算平衡-资产表_期末`, `${sjnd}_试算平衡-资产表_期初`],
        ItemName_total: '负债总计',
        tb_analyisis_name_tid: Md5_16(`试算分析-资产负债表_${isAudit.current}`),
      });
      if (!res.success) {
        notify('试算平衡表，未审财务报表、审定财务报表未初始化，请先初始化', 'error', 2000);
        return false;
      }
    } else {
      tb_names = [`${sjnd}_试算平衡-利润表_本期`, `${sjnd}_试算平衡-利润表_上期`];
      ItemName_total = '营业总收入';
    }
    let Assent = await buildTbtable({
      dbname: dbname,
      now_year_cmap: now_year_cmap,
      tb_analyisis_name: currentTableName.current,
      AuditedTypeNames: AuditedTypeNames,
      tb_names: tb_names,
      ItemName_total: ItemName_total,
    });

    if (!Assent.success) {
      notify('试算平衡表、未审财务报表、审定财务报表未初始化，请先初始化', 'error', 2000);
      return false;
    }
    return true;
  };

  /**
   * 页面数据初始化接口
   * @param isAllInit
   * @param yearTableName
   * @param actionTabs
   */
  const initloaddataApi = async (template: {
    isAllInit: boolean;
    yearTableName: any;
    actionTabs: any;
  }) => {
    setSpinLoad(true);

    await getAuditReportTemplate(
      template.isAllInit,
      template.yearTableName,
      template.actionTabs,
      builtableStrute,
    );

    setSpinLoad(false);
  };
  /**
   * 模板初始化接口
   * @param isAllInit
   * @param yearTableName
   * @param actionTabs
   * @returns
   */
  const getAuditReportTemplate = async (
    isAllInit: boolean,
    yearTableName: any,
    actionTabs: any,
    cb: any,
  ) => {
    try {
      const judg = await getjudgmentInit({
        dbname,
        type: 'fs',
        tableRealName: yearTableName,
      });
      if (judg.success) {
        console.log(refsCommonCpasTable.current, '@@@ ');
        if (judg.data?.count_number === 0) {
          const resTemp: any = await templateInitApi({
            dbName: dbname,
            templateFile: `${window?.main?.mainObject.getAppPath()}${basePath}\\TBAnalyisi.db`,
            type: 'fs',
            tableNames: [
              yearTableName,
              `试算分析-负债表_${isAudit.current}`,
              `试算分析-利润表_${isAudit.current}`,
            ],
          });

          // debugger;
          if (resTemp.success) {
            notify(`模板初始化成功`, 'success', 2000);
            if (!refsCommonCpasTable.current) return;
            const res = await cb('1');
            await refsCommonCpasTable.current.CPASInit2(yearTableName, res);
          } else {
            await refsCommonCpasTable.current.CPASInit2(yearTableName, false);
            if (resTemp?.msg) {
              notify(`${resTemp.msg}`, 'error', 2000);
            } else {
              notify(`模版初始化失败`, 'warning', 2000);
            }
          }
        } else {
          if (!refsCommonCpasTable.current) return;
          const res = await cb(valIndex);
          await refsCommonCpasTable.current.CPASInit2(yearTableName, res);
        }
      } else {
        notify(`获取判断是否初始化失败！`, 'error', 2000);
      }
    } catch (error) {
      console.log('li', error);
      notify(`获取判断是否初始化失败！程序异常`, 'error', 2000);
    }
  };

  const setPageLoading = (r: boolean, textLoad = '加载中...') => {
    setSpinLoad(!r);
    // settextLoad(textLoad);
  };

  // const changeSpinAntTabs = async (newData: boolean, yearTableName: any) => {
  //     setSpinAntTabs(newData);
  //     setIsInitBtn(false);
  //     setValIndex('1');
  //     if (newData && refsCommonCpasTable.current) {
  //         await getDesignTableName('');
  //         refsCommonCpasTable.current.CPASInit2('审定财务-资产表', false);
  //     }
  // }

  useEffect(() => {
    initloaddataApi({ isAllInit: true, yearTableName: currentTableName.current, actionTabs: '' });
  }, []);

  return (
    <div className="trialBalance_whole">
      {/* {spinLoad && <SpinLoading loadString="正在初始化 ..." />} */}
      <PageLoading isOpen={spinLoad} isMaskClose={false} content={'加载中'} width={200} />
      {spinAntTabs && (
        <AntTabs
          defaultActiveKey="1"
          className="changeTabsHeight"
          type="editable-card"
          destroyInactiveTabPane={true}
          onChange={(val: string) => {
            changeTabsKey(val);
          }}
          activeKey={valIndex}
          onEdit={() => {}}
          hideAdd={true}
        >
          {antTabsData.map((item) => (
            <AntTabs.TabPane
              tab={
                <div>
                  <span>{item.tabName}</span>
                </div>
              }
              key={item.tabKey}
              closable={item.closable}
            >
              <CommonCpasTable
                CPASTableProps={item.propsData}
                CPASTableTabName={item.tabName}
                initloaddataApi={initloaddataApi}
                excelParams={excelParams}
                setPageLoading={setPageLoading}
                ref={refsCommonCpasTable}
              />
            </AntTabs.TabPane>
          ))}
        </AntTabs>
      )}
    </div>
  );
};
export default ApprovedFinance;
